package com.hyfd.service.mp;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.GlobalSetHyfd;
import com.hyfd.common.Page;
import com.hyfd.dao.mp.AgentBillDiscountDao;
import com.hyfd.dao.mp.AgentDao;
import com.hyfd.dao.mp.AgentDataDiscountDao;
import com.hyfd.dao.mp.DataPkgDao;
import com.hyfd.dao.mp.ProviderDao;
import com.hyfd.service.BaseService;

@Service
@Transactional
public class AgentDataDiscountSer extends BaseService
{
    
    public Logger log = Logger.getLogger(this.getClass());
    
    @Autowired
    AgentDataDiscountDao agentDataDiscountDao;
    
    @Autowired
    AgentDao agentDao;
    
    @Autowired
    DataPkgDao dataPkgDao;
    
    @Autowired
    ProviderDao providerDao;
    
    @Autowired
    AgentBillDiscountDao agentBillDiscountDao;
    
    /**
     * 根据主键获取记录
     * 
     * @param id
     * @return
     */
    public Map<String, Object> getagentDataDiscountById(String id)
    {
        Map<String, Object> m = new HashMap<String, Object>();
        try
        {
            m = agentDataDiscountDao.selectByPrimaryKey(id);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return m;
    }
    
    /**
     * 获取记录数量
     * 
     * @param m
     * @return
     */
    public int getAgentDataDiscountCount(Map<String, Object> m)
    {
        int agentDataDiscountCount = 0;
        try
        {
            agentDataDiscountCount = agentDataDiscountDao.selectCount(m);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return agentDataDiscountCount;
    }
    
    /**
     * 根据条件分页获取代理商流量折扣列表数据并生成json
     * 
     * @param req
     * @return
     */
    public String agentDataDiscountList(String agentId, HttpServletRequest req)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            Map<String, Object> m = getMaps(req); // 封装前台参数为map
            m.put("agentId", agentId);
            Page p = getPage(m);// 提取分页参数
            int total = getAgentDataDiscountCount(m);
            p.setCount(total);
            int pageNum = p.getCurrentPage();
            int pageSize = p.getPageSize();
            
            sb.append("{");
            sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
            sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
            sb.append("" + getKey("records") + ":" + p.getCount() + ",");
            sb.append("" + getKey("rows") + ":" + "");
            
            PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
            List<Map<String, Object>> dataList = agentDataDiscountDao.getAgentDataDiscountList(m);
            String dataListJson = BaseJson.listToJson(dataList);
            sb.append(dataListJson);
            sb.append("}");
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        
        return sb.toString();
    }
    
    public String agentDataDiscountAdd(String agentId, HttpServletRequest req)
    {
        try
        {
            req.setAttribute("agentId", agentId);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return "mp/agentDataDiscountAdd";
    }
    
    /**
     * @功能描述： 根据条件获取全部代理商流量折扣列表数据并生成json
     *
     * @作者：HYJ @创建时间：2016年1月2日
     * @param req
     * @return
     */
    public String agentDataDiscountAllList(HttpServletRequest req)
    {
        String str = null;
        try
        {
            Map<String, Object> m = getMaps(req); // 封装前台参数为map
            List<Map<String, Object>> dataList = agentDataDiscountDao.selectAll(m);
            str = BaseJson.listToJson(dataList);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return str;
    }
    
    /**
     * 根据流量包、代理商、运营商查询折扣
     * */
    public String agentDataDiscountGet(HttpServletRequest req)
    {
        String str = "0";// 0代表没有折扣
        try
        {
            Map<String, Object> m = getMaps(req);
            String price = (String)m.get("price");
            Map<String, Object> agent = agentGetByUserId();
            String agentId = (String)agent.get("id");
            m.put("agentId", agentId);
            Map<String, Object> agentDataDiscount = agentDataDiscountDao.agentDataDiscountGet(m);
            if (agentDataDiscount != null)
            {
                // 计算折扣后价格
                String discount = agentDataDiscount.get("discount") + "";
                double pri = Double.parseDouble(price);
                double dis = Double.parseDouble(discount);
                BigDecimal b1 = new BigDecimal(pri);
                BigDecimal b2 = new BigDecimal(dis);
                Double disprice = new Double(b1.multiply(b2).doubleValue());
                NumberFormat nf = NumberFormat.getNumberInstance();
                // 保留两位小数
                nf.setMaximumFractionDigits(2);
                str = nf.format(disprice);
            }
            
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return str;
    }
    
    /**
     * 添加代理商流量折扣信息
     * 
     * @param req
     * @return
     */
    public String agentDataDiscountAdd(HttpServletRequest req)
    {
        Session session = getSession();
        Map<String, Object> map = getMaps(req);
        String agentId = (String)map.get("agentId");
        boolean flag = false;
        try
        {
            String name = (String)map.get("name");
            String providerId = (String)map.get("providerId");
            String dataType = (String)map.get("dataType");
            if (providerId != null && providerId != "" && agentId != null && agentId != "" && dataType != null
                && dataType != "")
            {
                map.remove("name");
                List<Map<String, Object>> allList = agentDataDiscountDao.selectAll(map);
                if (allList.size() > 0)
                {
                    int i = agentDataDiscountDao.delByAgentAndProvider(map);
                    map.remove("dataType");
                    map.remove("providerId");
                    map.remove("agentId");
                    flag = agentDataDiscount(name, agentId, providerId, dataType, map);
                }
                else
                {
                    map.remove("dataType");
                    map.remove("providerId");
                    map.remove("agentId");
                    flag = agentDataDiscount(name, agentId, providerId, dataType, map);
                }
            }
            else
            {
                session.setAttribute(GlobalSetHyfd.backMsg, "参数不完整,添加失败");
            }
            session.setAttribute(GlobalSetHyfd.backMsg, flag ? "添加成功" : "添加失败!");
        }
        catch (Exception e)
        {
            session.setAttribute(GlobalSetHyfd.backMsg, flag ? "添加成功" : "添加失败!");
            getMyLog(e, log);
        }
        return "redirect:agentDataDiscountListPage/" + agentId;
    }
    
    public boolean agentDataDiscount(String name, String agentId, String providerId, String dataType,
        Map<String, Object> map)
    {
        boolean flag = false;
        try
        {
            Map<String, Object> userInfoMap = getUser(); // 取到当前用户信息
            for (Map.Entry<String, Object> entry : map.entrySet())
            {
                String provinceCode = entry.getKey();
                String discount = (String)entry.getValue();
                if (discount != null && discount != "")
                {
                    Map<String, Object> m = new HashMap<String, Object>();
                    m.put("name", name);
                    m.put("agentId", agentId);
                    m.put("providerId", providerId);
                    m.put("provinceCode", provinceCode);
                    m.put("dataType", dataType);
                    m.put("discount", discount);
                    List<String> dataPkgByProId = dataPkgDao.getPkgId(m);
                    if (dataPkgByProId.size() > 0)
                    {
                        for (String dataPkgId : dataPkgByProId)
                        {
                            m.put("createUser", userInfoMap.get("suName"));// 放入用户
                            m.put("dataPkgId", dataPkgId);
                            int i = agentDataDiscountDao.insertSelective(m);
                            if (i > 0)
                            {
                                flag = true;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            flag = false;
            getMyLog(e, log);
        }
        
        return flag;
    }
    
    // /**
    // * 修改代理商流量折扣信息
    // * @param req
    // * @param id
    // * @return
    // */
    // public String agentDataDiscountEdit(HttpServletRequest req){
    // String agentId =null;
    // boolean flag=false;
    // Session session=getSession();
    // try{
    // Map<String, Object> myData=getMaps(req);
    // agentId = (String) myData.get("agentId");
    // Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
    // myData.put("updateUser", userInfoMap.get("suName"));//放入用户
    // int rows=agentDataDiscountDao.updateByPrimaryKeySelective(myData);
    // if(rows>0){
    // flag=true;
    // }
    // session.setAttribute(GlobalSetHyfd.backMsg, flag?"修改成功":"修改失败");
    // }catch(Exception e){
    // session.setAttribute(GlobalSetHyfd.backMsg, flag?"修改成功":"修改失败");
    // getMyLog(e,log);
    // }
    // return "agentDataDiscountListPage/"+agentId;
    // }
    //
    /**
     * 修改代理商流量折扣
     * 
     * @param req
     * @param id
     * @return
     */
    public String agentDataDiscountUpdate(HttpServletRequest req)
    {
        String flag = "";
        try
        {
            Map<String, Object> myData = getMaps(req);
            Map<String, Object> userInfoMap = getUser(); // 取到当前用户信息
            String agentId = (String)myData.get("agentId");
            String providerId = (String)myData.get("providerId");
            String provinceCode = (String)myData.get("provinceCode");
            String discountMeg = (String)myData.get("discountMeg");
            if (agentId != null && agentId != "" && providerId != null && providerId != "" && provinceCode != null
                && provinceCode != "" && discountMeg != null && discountMeg != "")
            {
                String[] data = discountMeg.split(",");
                for (String dataMeg : data)
                {
                    Map<String, Object> param = new HashMap<String, Object>();
                    String[] split = dataMeg.split("-");
                    String dataPkgId = split[0];
                    String discount = "";
                    if (split.length > 1)
                    {
                        discount = split[1];
                    }
                    param.put("agentId", agentId);
                    param.put("providerId", providerId);
                    param.put("provinceCode", provinceCode);
                    param.put("dataPkgId", dataPkgId);
                    // 根据代理商ID运营商ID省份和包查询是否有折扣
                    Map<String, Object> agentDiscount = agentDataDiscountDao.agentDataDiscountGet(param);
                    if (agentDiscount != null)
                    {// 有折扣的操作
                        if (discount != "")
                        {// 如果前台传来的折扣不为空就修改
                            param.put("discount", discount);
                            param.put("updateUser", userInfoMap.get("suName"));// 放入修改用户
                            int i = agentDataDiscountDao.updateDiscount(param);
                            if (i > 0)
                            {
                                flag = "更新成功";
                            }
                            else
                            {
                                flag = "更新失败";
                                break;
                            }
                        }
                        else
                        {// 前台传来折扣为空，则删除
                            int i = agentDataDiscountDao.deleteDiscount(param);
                            if (i > 0)
                            {
                                flag = "更新成功";
                            }
                            else
                            {
                                flag = "更新失败";
                                break;
                            }
                        }
                    }
                    else
                    {// 没有折扣
                        if (discount != "")
                        {// 如果折扣不为空就添加
                            param.put("discount", discount);
                            param.put("createUser", userInfoMap.get("suName"));// 放入添加用户
                            int i = agentDataDiscountDao.insertSelective(param);
                            if (i > 0)
                            {
                                flag = "更新成功";
                            }
                            else
                            {
                                flag = "更新失败";
                                break;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return flag;
    }
    
    /**
     * 带着代理商Id跳转到代理商流量折扣页
     * 
     * @param id
     * @return
     */
    public String agentDataDiscountListPage(String id, HttpServletRequest req)
    {
        try
        {
            req.setAttribute("agentId", id);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return "mp/agentDataDiscountList";
    }
    
    /**
     * 跳转到代理商流量折扣编辑页
     * 
     * @param id
     * @return
     */
    public String agentDataDiscountPage(String id, HttpServletRequest req)
    {
        try
        {
            String[] ids = req.getParameterValues("ids");
            req.setAttribute("agentId", id);
            req.setAttribute("ids", ids);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return "agentDataDiscountEditPage";
    }
    
    public String agentDataDiscountEditPage(HttpServletRequest req)
    {
        return "mp/agentDataDiscountEdit";
    }
    
    /**
     * 带着agentId跳转到代理商话费折扣详情页
     * 
     * @param id
     * @return
     */
    public String agentDataDiscountDetailPage(String id, HttpServletRequest req)
    {
        try
        {
            Map<String, Object> agent = agentDao.selectById(id);
            req.setAttribute("agent", agent);
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return "mp/agentDataDiscountDetail";
    }
    
    /**
     * 详情页数据
     * */
    public String agentDataDiscountDetail(String agentId, HttpServletRequest req)
    {
        String str = "";
        try
        {
            Map<String, Object> map = getMaps(req);
            String providerId = (String)map.get("providerId");
            String province = (String)map.get("provinceCode");
            String dataType = (String)map.get("dataType");
            if (providerId != null && providerId != "" && province != null && province != "" && dataType != null
                && dataType != "")
            {
                map.put("agentId", agentId);
                List<Map<String, Object>> selectListByDataType = agentDataDiscountDao.selectByDataType(map);
                if (selectListByDataType.size() > 0)
                {
                    str = BaseJson.listToJson(selectListByDataType);
                }
            }
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return str;
    }
    
    /**
     * 查询该代理商所在通道的流量包
     * */
    public String agentDataDiscountPkgList(String agentId, HttpServletRequest req)
    {
        String str = "false";
        try
        {
            Map<String, Object> map = getMaps(req);
            map.put("agentId", agentId);
            List<Map<String, Object>> dataPkgList = dataPkgDao.getDataPkgByProId(map);
            if (dataPkgList.size() > 0)
            {
                str = BaseJson.listToJson(dataPkgList);
            }
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        return str;
    }
    
    // /**
    // * 删除代理商流量折扣信息
    // * @param id
    // * @return
    // */
    // public String agentDataDiscountDel(String agentId,HttpServletRequest req){
    // try{
    // boolean flag=false;
    // String[] ids = req.getParameterValues("ids");
    // for(String id:ids){
    // int rows=agentDataDiscountDao.deleteByPrimaryKey(id);
    // if(rows>0){
    // flag=true;
    // }else{
    // flag=false;
    // break;
    // }
    // }
    // Session session=getSession();
    // session.setAttribute(GlobalSetHyfd.backMsg, flag?"删除成功":"删除失败");
    //
    // }catch(Exception e){
    // getMyLog(e,log);
    // }
    // return "agentDataDiscountListPage/"+agentId;
    // }
    
    public String queryAgentDiscountBySuId(String suId, HttpServletRequest req)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            Map<String, Object> agentMap = agentDao.selectByUserId(suId);
            Map<String, Object> m = getMaps(req);
            m.put("agentId", agentMap.get("id"));
            Page p = getPage(m);// 提取分页参数
            int total = agentDataDiscountDao.selectCountByAgentId(m);
            p.setCount(total);
            int pageNum = p.getCurrentPage();
            int pageSize = p.getPageSize();
            
            sb.append("{");
            sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
            sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
            sb.append("" + getKey("records") + ":" + p.getCount() + ",");
            sb.append("" + getKey("rows") + ":" + "");
            
            PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
            List<Map<String, Object>> dataList = agentDataDiscountDao.getAgentDataDiscountPkgListBySuId(m);
            String dataListJson = BaseJson.listToJson(dataList);
            sb.append(dataListJson);
            sb.append("}");
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        
        return sb.toString();
    }
    
    public String queryAgentBillDiscountBySuId(String suId, HttpServletRequest req)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            Map<String, Object> agentMap = agentDao.selectByUserId(suId);
            Map<String, Object> m = getMaps(req);
            m.put("agentId", agentMap.get("id"));
            Page p = getPage(m);// 提取分页参数
            int total = agentBillDiscountDao.selectCountByAgentId(m);
            p.setCount(total);
            int pageNum = p.getCurrentPage();
            int pageSize = p.getPageSize();
            
            sb.append("{");
            sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
            sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
            sb.append("" + getKey("records") + ":" + p.getCount() + ",");
            sb.append("" + getKey("rows") + ":" + "");
            
            PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
            List<Map<String, Object>> dataList = agentBillDiscountDao.getAgentBillDiscountPkgListBySuId(m);
            String dataListJson = BaseJson.listToJson(dataList);
            sb.append(dataListJson);
            sb.append("}");
        }
        catch (Exception e)
        {
            getMyLog(e, log);
        }
        
        return sb.toString();
    }
    
}
